define([
        "require",
        "jQuery",
        "core",
        "tools",
        "scanSelect"
    ], function (require, jQuery, core, tools, scanSelect) {
        var list = {};
        list.urls;
        var options = {};
        options.recordIdName = "record-id";
        options.actionEdit = "record-id";
        options.urlList = "list";
        options.targetSelector = ".content";
        options.searchFormSelector = "#fuzzySearchListForm";
        options.recordFormSelector = "#recordForm";
        options.recordAttr = "record-attr";
        options.recordAttr2 = "record-attr2";
        options.formTitle = "form-title";
        options.saveBtnContent = "save-btn-content";
        options.insertAction = function () {
        };
        options.updateAction = function () {
        };
        options.deleteAction = function () {
        };

        function getFormTitle(prefix) {
            var title = $(".table:first").data("formName");
            if (prefix !== undefined && !core.isEmpty(title))
                title = prefix + title;
            return title;
        }

        function getRecordId() {
            return $(this).closest("[" + options.recordIdName + "]").attr(options.recordIdName);
        }

        function getRecordAttr() {
            return $(this).closest("[" + options.recordAttr + "]").attr(options.recordAttr);
        }

        function getRecordAttr2() {
            return $(this).closest("[" + options.recordAttr2 + "]").attr(options.recordAttr2);
        }

        list.addViewEventOnly = function(modalSelector, basePath){
            var urls = new core.Urls(core.getUrl(basePath));
            addViewEvent(modalSelector, urls);
        }

        function addViewEvent(modalSelector, urls) {
            var nodes = $("[record-id]").find("td").filter(function () {
                if (!$(this).hasClass("popup-close")) return true;
                else return false;
            });

            nodes.unbind("click").click(function () {
                var id = $(this).parent().attr(options.recordIdName);
                var formTitle = getFormTitle("查看");
                var recordExtendAttr = getRecordAttr.call(this);
                if (!core.isEmpty(recordExtendAttr) && getRecordAttr2.call(this) === 'true') {
                    core.showForm(modalSelector, {
                        formUrl: urls.viewByAttr(id, recordExtendAttr),
                        formTitle: formTitle
                    });
                } else {
                    core.showForm(modalSelector, {
                        formUrl: urls.view(id),
                        formTitle: formTitle
                    });
                }
            });

            nodes.css({cursor: "pointer"});
        }

        function addEditEvent(modalSelector, urls) {
            var nodes = $(".action-edit");
            nodes.click(function () {
                var id = getRecordId.call(this);
                var formTitle = getFormTitle("编辑");
                var recordExtendAttr = getRecordAttr.call(this);

                if (!core.isEmpty(recordExtendAttr) && getRecordAttr2.call(this) === 'true') {
                    core.showForm(modalSelector, {
                        formUrl: urls.editByAttr(id, recordExtendAttr),
                        postUrl: urls.update(),
                        successUrl: urls.list(),
                        formTitle: formTitle
                    }, options.updateAction);
                } else {
                    core.showForm(modalSelector, {
                        formUrl: urls.edit(id),
                        postUrl: urls.update(),
                        successUrl: urls.list(),
                        formTitle: formTitle
                    }, options.updateAction);
                }
            });
        }

        function addInsertEvent(modalSelector, urls) {
            var nodes = $(".action-insert");
            nodes.click(function () {
                core.showForm(modalSelector, {
                    formUrl: urls.new(),
                    postUrl: urls.insert(),
                    successUrl: urls.list(),
                    formTitle: getFormTitle("新增")
                }, options.insertAction);
            });
        }

        function addDeleteEvent(urls) {
            var nodes = $(".action-delete");
            nodes.click(function () {
                var id = getRecordId.call(this);
                var formTitle = getFormTitle("删除");

                tools.confirm({
                    message: "确定删除!",
                    title: formTitle,
                    callback: function (result) {
                        if (result) {
                            $.ajax({
                                url: urls.delete(id),
                                type: "delete",
                                dataType: "json",
                                success: function (msg) {
                                    if (core.isSuccess(msg)) {
                                        core.loadContent(list.urls.list());
                                    }

                                    options.deleteAction();
                                    tools.notice(msg.info);
                                }
                            })
                        }
                    }
                });
            });
        }

        /**
         * 带有查询默认参数的delete方法，避免有固定参数的list delete后返回所有数据list
         * @param urls
         */
        function addDeleteEvent2(searchFormSelector, urls) {
            var nodes = $(".action-delete2");
            nodes.click(function () {
                var id = getRecordId.call(this);

                var r = confirm("确定删除!");
                if (r == true) {
                    $.ajax({
                        url: urls.delete(id),
                        type: "delete",
                        dataType: "json",
                        success: function (msg) {
                            if (core.message(msg)) {
                                // core.loadContent(list.urls.list());
                                submitSearch(searchFormSelector, list.urls.list());
                            }
                            options.deleteAction();
                        }
                    })
                }
            });
        }

        function submitSearch(formSelector, url) {
            // console.log(formSelector + " " + url + " " + options.targetSelector);
            // console.log($(formSelector).serialize());

            $.ajax({
                url: url,
                type: "POST",
                data: $(formSelector).serialize(),
                success: function (data) {
                    $(options.targetSelector).html("");
                    $(options.targetSelector).html(data);
                },
                error: function (data) {
                    core.message(data);
                }
            });
        }

        function addPaginationList(searchListFormSelector, urls) {
            var linksNum = 3;
            var pageIndex = parseInt($("#pageIndex").val());
            var pageSize = parseInt($("#pageSize").val());
            var pagesNum = parseInt($("#pagesNum").val());
            var pagination = $(".pagination-list").append('<ul class="pagination pagination-sm no-margin pull-right">');
            var ul = pagination.children().eq(0);

            ul.append('<li>' +
                '<span class="paginate-button previous" href="#" >上一页</span></li>');
            if (pageIndex > linksNum + 1) {
                ul.append('<li>' +
                    '<span class="paginate-button" href="#">...</span>' +
                    '</li>');
            }

            for (var i = pageIndex - linksNum; i <= pageIndex + linksNum; i++) {
                var aClass = "paginate-button";
                if (i == pageIndex) aClass = "paginate-current";

                if (i > 0 && i <= pagesNum)
                    ul.append('<li>' +
                        '<span class="' + aClass + '" paginate-index="' + i + '" href="#">' + i + '</span>' +
                        '</li>');
            }
            if (pageIndex + linksNum < pagesNum) {
                ul.append('<li>' +
                    '<span class="paginate-button" href="#">...</span>' +
                    '</li>');
            }
            ul.append('<li>' +
                '<span class="paginate-button next" href="#">下一页</span></li>');

            if (pageIndex == 1) $("span.previous").addClass("disabled");
            else $("span.previous").css({cursor: "pointer"}).attr("paginate-index", pageIndex - 1);
            if (pageIndex == pagesNum || pagesNum == 0) $("span.next").addClass("disabled");
            else $("span.next").css({cursor: "pointer"}).attr("paginate-index", pageIndex + 1);

            $("span[paginate-index]").css({cursor: "pointer"}).on("click", function (e) {
                var index = $(this).attr("paginate-index");
                $("#pageIndex").val(index);//Set page num is 1
                submitSearch(searchListFormSelector, urls.list());
            })
        }

        function addPaginationOverview() {
            $.each($(".pagination-overview"), function () {
                var elem = $(this);
                var startRow = elem.data("startRow").toString();
                var endRow = elem.data("endRow").toString();
                var totalNum = elem.data("totalNum").toString();

                elem.append(
                    '共有' + totalNum + '条，当前显示第' + startRow + '到第' + endRow + '条数据'
                );
            })
        }

        function addSearchEvent(searchListFormSelector, urls) {
            function submit() {
                $("#fuzzyField").val($("#fuzzyFieldStr").val());
                $("#pageIndex").val(1);//Set page num is 1
                submitSearch(searchListFormSelector, urls.list());
            }

            $(".search-button").unbind("click").on("click", submit);
            $(".search-input").keydown(function (event) {
                if (event.which == 13) {
                    submit()
                }
            });
        }

        function addExportEvent(urls) {
            $(".action-export").unbind("click").on("click", function () {
                window.open(urls.export());
            });
        }

        function init(basePath, searchFormSelector, modalSelector) {
            list.urls = new core.Urls(core.getUrl(basePath));
            list.urls.list = function () {
                return core.getUrl(this._baseUrl + "/" + options.urlList);
            };
            list.urls.insert = function () {
                return core.getUrl(this._baseUrl + "/rest/" + options.urlInsert);
            };
            list.urls.update = function () {
                return core.getUrl(this._baseUrl + "/rest/" + options.urlUpdate);
            };

            addPaginationList(searchFormSelector, list.urls);
            addPaginationOverview();
            addSearchEvent(searchFormSelector, list.urls);
            addViewEvent(modalSelector, list.urls);
            addInsertEvent(modalSelector, list.urls);
            addEditEvent(modalSelector, list.urls);
            addDeleteEvent(list.urls);
            addDeleteEvent2(searchFormSelector, list.urls);
            addExportEvent(list.urls);
        }

        list.initFuzzySearchList = function (basePath, extOptions) {
            scanSelect.initSelect();
            // 避免其他调用的时候，把默认值给覆盖掉了，所以重新初始化下。
            options = $.extend({}, options, {
                recordIdName: "record-id",
                actionEdit: "record-id",
                urlList: "list",
                urlInsert: "insert",
                urlUpdate: "update",
                targetSelector: ".content",
                searchFormSelector: "#fuzzySearchListForm",
                modalSelector: "#modal",
                recordAttr: "record-attr",
                recordAttr2: "record-attr2"
            });
            options = $.extend({}, options, extOptions);
            init(basePath, options.searchFormSelector, options.modalSelector);
        };

        list.initSearchList = function (basePath, extOptions) {
            // 避免其他调用的时候，把默认值给覆盖掉了，所以重新初始化下。
            options = $.extend({}, options, {
                recordIdName: "record-id",
                actionEdit: "record-id",
                urlList: "list",
                urlInsert: "insert",
                urlUpdate: "update",
                targetSelector: ".content",
                searchFormSelector: "#searchListForm",
                modalSelector: "#modal",
                recordAttr: "record-attr",
                recordAttr2: "record-attr2"
            });
            options = $.extend({}, options, extOptions);
            init(basePath, options.searchFormSelector, options.modalSelector);
        };

        return list;
    }
);